<!--
	作者：1048107945@qq.com
	时间：2020-02-29
	描述：工资补发主页面
-->
<template>
  <div class="app-container clearfix">
    <!-- 列表 -->
    <salarymake-table
      :id="id"
      :data="listData"
      :search-params="searchKey"
      :total-count="totalCount"
      :list-loading="listLoading"
      :type="type"
      :dept-name="deptName"
      :salary-date="searchKey.salaryDate | formatDate('yyyy-MM')"
      :params-data="paramsData"

      @on-delete="handleDelete"
      @on-reelect="handleReelect"
      @on-redo="handleRedo"
      @on-bufa="handleBufa"
      @on-save="handleSave"
      @on-approve="handleApprove"
      @on-export="handleExport"
      @on-init="handleInitList"
      @on-edit="handleEditShow"
    />
    <!-- 选择部门和月份弹出框 -->
    <salarymake-select
      :visible.sync="isShowSelectParams"
      :department-all-list-data="departmentAllListData"
    />

    <!-- 员工选择弹出框 -->
    <empchoose
      :params-data="paramsData"
      :visible.sync="empchooseInfo.visible"
      :detail-data="empchooseInfo.datalist"
      @choose-emp-list="chooseEmpList"
    />

  </div>
</template>

<script>
import {
  getEmployeeListCreateAPI,
  getEmployeeListUpdateAPI,
  saveSalarymakeAPI, saveSalarymakeAPI2, saveSalarymakeAPI3,
  redoSalarymakeAPI,
  submitApproveAPI, submitApproveAPI2,
  exportListAPI, exportListAPI2
} from '@/api/todo/salarymake'
import { SalarymakeTable, SalarymakeSelect } from './components'
import { formatDate, formatTimestamp } from '@/utils/utils'
import commonMixins from '@/mixins/common'
import treeAllListData from '@/mixins/treeAllListData'
import salaryImportExcel from '@/mixins/salaryImportExcel2'
import filters from '@/filters/filters'
import empchoose from './components/empchoose'

export default {
  name: 'SalarymakeList',
  components: {
    SalarymakeTable,
    SalarymakeSelect,
    empchoose
  },
  mixins: [commonMixins, filters, treeAllListData, salaryImportExcel],
  props: {},
  data() {
    return {
      type: '1', // 1、新增 2、修改 3、查看
      id: '', // 月薪列表ID
      initParams: { // 初始化参数
        pageNum: 1, // 当前页数
        pageSize: 10, // 每页个数
        sort: '', // 排序
        deptId: null, // 部门ID
        salaryDate: '' // 发放月份
      },
      searchKey: {}, // 搜索参数
      editInfo: { // 编辑弹出框
        visible: false, // 是否显示模态框
        detailInfo: {}
      },
      totalCount: 0, // 分页用的列表总条数
      listLoading: false,
      isShowSelectParams: false, // 如果没有选择部门或者月份就显示弹出框
      deptName: '',
      importInstance: undefined,
      listData: [], // 列表数据

      paramsData: {}, // 用于接收其他页面传递过来的参数

      empchooseInfo: {
      		visible: false,
      		datalist: [],
      		chosenList: []
      	}
    }
  },
  computed: {},
  watch: {
    initParams: {
      handler: function(newVal, oldVal) {
        if (JSON.stringify(newVal) !== JSON.stringify(this.searchKey)) {
          this.searchKey = JSON.parse(JSON.stringify(newVal))
        }
      },
      deep: true,
      immediate: true
    },
    isShowSelectParams(newVal, oldVal) {
      const { id, type } = this
      const { deptId, salaryDate } = this.searchKey
      if (!newVal && (!deptId || !salaryDate)) {
        this.$nextTick(() => {
          // this.isShowSelectParams = true
          this.$notify.error({
            title: '错误',
            message: '必须要选择部门和发放月份!'
          })
        })
      }
    }
  },
  created() {
  },
  mounted() {
    	 const query = this.$router.query
    	 console.log(query)
  },
  methods: {

    	// 补发工资 - 选择员工后触发
    	chooseEmpList(listData) {
    		console.log('本次选择的员工有', listData.length)

    		for (let i = 0; i < listData.length; i++) {
    			// 检查列表中是否存在了选择的员工
    			for (let j = 0; j < this.listData.length; j++) {
    				if (this.listData[j].employeeId == listData[i].employeeId) {
    					this.$notify.error({
			                title: '错误',
			                message: listData[i].employeeName + '已经存在于补发列表中了，请不要重复勾选！请点击查询按钮重新选择。'
			              })

    					// location.reload()

    					// 重置选择员工列表
    					/* console.log(this.empchooseInfo.datalist)
    					this.empchooseInfo.datalist = this.empchooseInfo.datalist;*/
    					return
    				}
    			}

    			listData[i].realSalary = 0 // 实发工资
			    listData[i].beforeTaxSalary = 0 // 税前工资
			    listData[i].personalIncomeTax = 0// 个税

    			this.listData.push(listData[i]) // 直接push，如果listData有值（编辑的情况），就保留
    		}

    		// 去重
    		/* let arr = this.listData.slice(0);
    		let newArr = [];
    		for(let i = 0;i < listData.length;i++){
    			let exist = false;
    			for(let j=0;j<newArr.length;j++){
    				if(newArr[j].employeeId == arr[i].employeeId){
    					exist = true;
    				}
    			}

    			if(!exist){
    				newArr.push(arr[i]);
    			}

    		}*/
    		// this.listData = newArr;
    		this.totalCount = 	this.listData.length
    		console.log('新的员工列表：', this.listData)
    	},
    goBack() {
      this.$router.replace({
        name: 'Salary'
      })
    },
    goSalaryreissue({ type, data }) { // 进入工资补发
      let query = { type }
      if (type === '1') {
        query = {
          ...query,
          ...data
        }
      } else {
        query['id'] = data.id
      }
      // console.log(query)
      this.$router.push({
        name: 'Salaryreissue',
        query
      })
    },
    formatParams(listData) { // 格式化参数
      const { id, type } = this
      const { deptId, salaryDate } = this.searchKey
      const params = {
        salaryType: this.paramsData.salaryType,
        title: this.paramsData.title,
        salaryMonth: salaryDate,
        deptId: deptId,
        hrSalaryMonths: []
      }
      listData.forEach((item, index) => {
        params.hrSalaryMonths[index] = {
          ...item,
          ...{
            salaryDate: salaryDate,
            deptId: deptId
          }
        }
      })
      if (type !== '1') { // 修改、查看
        params.id = id
      }
      // console.log(params)
      // console.log(JSON.stringify(params))

      // 如果是补发，重新拼接参数

      params.hrSalaryMonthReissues = []

      console.log('原提交的参数', params)

      if (this.paramsData.salaryType == 20) {
        const hrSalaryMonthReissues = params.hrSalaryMonths.slice(0) // 拷贝数组
        params.hrSalaryMonths = []
        for (let i = 0; i < hrSalaryMonthReissues.length; i++) {
        	params.hrSalaryMonthReissues.push({
        	personalIncomeTax: hrSalaryMonthReissues[i].personalIncomeTax,
            bankNo: hrSalaryMonthReissues[i].bankNo,
            beforeTaxSalary: hrSalaryMonthReissues[i].beforeTaxSalary,
            certNo: hrSalaryMonthReissues[i].certNo,
            createBy: hrSalaryMonthReissues[i].createBy,
            createName: hrSalaryMonthReissues[i].createName,
            createTime: hrSalaryMonthReissues[i].createTime,
            dataScope: hrSalaryMonthReissues[i].dataScope,
            deptId: hrSalaryMonthReissues[i].deptId,
            deptName: hrSalaryMonthReissues[i].deptName,
            employeeId: hrSalaryMonthReissues[i].employeeId,
            employeeName: hrSalaryMonthReissues[i].employeeName,
            employeeStatus: hrSalaryMonthReissues[i].employeeStatus,
            employeeStatusDesc: hrSalaryMonthReissues[i].employeeStatusDesc,
            //								enterpriseSocialSecurityTotalCost: 200.16
            id: hrSalaryMonthReissues[i].id,
            labourServiceSalary: hrSalaryMonthReissues[i].labourServiceSalary,
            labourServiceTax: hrSalaryMonthReissues[i].labourServiceTax,
            leaveDate: hrSalaryMonthReissues[i].leaveDate,
            marketingSalary: hrSalaryMonthReissues[i].marketingSalary,
            onboardingDate: hrSalaryMonthReissues[i].onboardingDate,
            openingBank: hrSalaryMonthReissues[i].openingBank,
            payableSalary: hrSalaryMonthReissues[i].payableSalary,
            phone: hrSalaryMonthReissues[i].phone,
            postId: hrSalaryMonthReissues[i].postId,
            postIds: hrSalaryMonthReissues[i].postIds,
            postName: hrSalaryMonthReissues[i].postName,
            realSalary: hrSalaryMonthReissues[i].realSalary,
            remark: hrSalaryMonthReissues[i].remark,
            salaryDate: hrSalaryMonthReissues[i].salaryDate,
            salaryPost: hrSalaryMonthReissues[i].salaryPost,
            salaryType: hrSalaryMonthReissues[i].salaryType,
            searchValue: hrSalaryMonthReissues[i].searchValue,
            socialInsurancePlace: hrSalaryMonthReissues[i].socialInsurancePlace,
            status: hrSalaryMonthReissues[i].status,
            submissionId: hrSalaryMonthReissues[i].submissionId,
            //								subsidySalary: 0
            //								teacherMealSalary: 0
            updateBy: hrSalaryMonthReissues[i].updateBy,
            updateTime: hrSalaryMonthReissues[i].updateTime
          })
        }
      }

      return params
    },
    handleReelect() { // 重新选择部门和月份
      this.isShowSelectParams = true
    },
    handleEditShow(data = {}) { // 编辑－显示弹出框
      this.editInfo.visible = true
      this.editInfo.detailInfo = data
    },
    handleCreated() { // 添加成功
      this.searchKey.page = 1
      this.getListData()
    },
    handleUpdated() { // 编辑成功
      this.getListData()
    },
    handleInitList(params = {}) { // 初始化列表
      this.searchKey = {
        ...this.searchKey,
        ...params
      }
      this.getListData()
    },
    handleSave(listData) { // 保存
      const pnum = listData.length
    	  if (listData.length == 0) {
        this.$notify.error({
          title: '错误',
          message: '没有补发数据！'
        })
        return
      }

      const params = this.formatParams(listData)

      if (!params.title) {
        params.title = this.paramsData.title
      }

      console.log(this.paramsData)
      params.pnum = pnum
      this.saveData(params)
    },
    handleRedo() { // 重做
      this.$confirm(`是否确定重做，重做后之前数据不可恢复！！！`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.getRedoListData()
      }).catch(() => {
      })
    },

    handleDelete(id) {
      this.listData.splice(this.listData.findIndex(item => item.id === id), 1)
      this.totalCount = this.listData.length
    },

    handleBufa() {
      	/* this.$confirm(`是否确定补发?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {*/

      // 打开补发窗口
      this.empchooseInfo.visible = true
      // console.log(this.listData);

      // this.empchooseInfo.datalist = list;

      /*  }).catch(() => {
        })*/
    },

    handleApprove(listData) { // 是否审批
      this.$confirm(`是否提交进入审批流程?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (listData.length == 0) {
          this.$notify.error({
            title: '错误',
            message: '没有补发数据！'
          })
          return
        }

        const params = this.formatParams(listData)
        params.pnum = listData.length
        this.submitApproveData(params)
      }).catch(() => {
      })
    },
    handleExport() { // 导出按钮操作
      const { id, type } = this
      if (type === '1' && !id) {
        this.$notify.error({
          title: '错误',
          message: '请先保存数据！'
        })
      } else {
        this.$confirm('请先保存后再导出Excel文件！', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          try {
            let response = null

		          // 补发
		          if (this.paramsData.salaryType == 20) {
		          	response = await exportListAPI2({
			            id
			          })
		          } else if (this.paramsData.salaryType == 11) {
		          	response = await exportListAPI3({
			            id
			          })
		          } else {
		          	// 正常月工资
		          	response = await exportListAPI({
			            id
			          })
		          }

            this.downloadFile(response)
          } catch (error) {
            // console.log(error)
            this.$notify.error({
              title: '错误',
              message: error.message || '操作失败！'
            })
          }
        }).catch(() => {
        })
      }
    },
    async getRedoListData() { // 获取重做列表数据
      try {
        const { id } = this
        this.listLoading = true
        const response = await redoSalarymakeAPI({
          id: id
        })
        const result = response
        if (+result.code === 200) {
          const resultData = result.data.hrSalaryMonths || []
          this.listData = resultData.map((item) => {
            item.baseSalary = item.salaryBase
            item.assessmentSalary = item.salaryAssessment
            item.postSalary = item.salaryPost
            item.allowanceSalary = item.salaryAllowance
            return item
          })
          this.totalCount = result.data.hrSalaryMonths.length
        } else {
          this.$notify.error({
            title: '错误',
            message: result.msg || '获取列表失败！'
          })
        }
      } catch (error) {
        // console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message || '获取列表失败!'
        })
      } finally {
        this.listLoading = false
      }
    },
    async submitApproveData(params) { // 审批－请求数据
      try {
        this.listLoading = true

        let response = null
        // alert(this.paramsData.salaryType)
        // 补发
        if (this.paramsData.salaryType == 20) {
          	// alert();

          	console.log('本次提交的参数')
          	console.log(params)

          	response = await submitApproveAPI2({
	            ...params
	          })
        } else {
          	// 正常月工资
          	response = await submitApproveAPI({
	            ...params
	          })
        }

        const result = response
        if (+result.code === 200) {
          this.goBack()
          this.$notify({
            title: '成功',
            message: result.msg || '审批提交成功！',
            type: 'success',
            duration: 4000
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: result.msg || '审批提交失败！'
          })
        }
      } catch (error) {
        // console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message || '审批提交失败！'
        })
      } finally {
        this.listLoading = false
      }
    },
    async saveData(params = {}) { // 保存－请求数据
      try {
        const { type } = this
        this.listLoading = true
        /* <<<<<<< Updated upstream
          let response = await saveSalarymakeAPI({
            ...params,
            ...{
              title: '123'
            }
          })
=======*/

        let response = null

        // 补发
        if (this.paramsData.salaryType == 20) {
          	response = await saveSalarymakeAPI2({
	            ...params
	          })
        } else if (this.paramsData.salaryType == 11) {
          	response = await saveSalarymakeAPI3({
	            ...params
	          })
        } else {
          	// 正常月工资
          	response = await saveSalarymakeAPI({
	            ...params
	          })
        }

        const result = response
        if (+result.code === 200) {
          this.$notify({
            title: '成功',
            message: '保存成功！',
            type: 'success',
            duration: 2000
          })
          if (type === '1') {
            const id = result.data.id // 得到反回的submitid，作为查询的条件
            const data = this.paramsData

            data.id = id

            console.log(data)

            this.goSalaryreissue({
					    type: '2', // 修改
					    data: data
            })
          }
        } else {
          this.$notify.error({
            title: '错误',
            message: result.msg || '保存失败！'
          })
        }
      } catch (error) {
        // console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message || '保存失败！'
        })
      } finally {
        this.listLoading = false
      }
    },
    async getDepartmentAllListData() { // 获取所有数据
      try {
        await this.$store.dispatch('department/GetDepartmentList', {
          request: true,
          showChargedOnly: true
        })
      } catch (error) {
        // console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message
        })
      }
    },

    // 保存后也会调用
    async getListData() { // 获取列表数据
      try {
        const { id, type, searchKey } = this
        this.listLoading = true
        let response
        if (type === '1') { // 新增获取员工列表接口
          response = await getEmployeeListCreateAPI({
            ...searchKey,
            ...{
              salaryType: 20
            }
          })
        } else { // 修改、查看获取员工列表接口
          response = await getEmployeeListUpdateAPI({
            id: id
          })
        }
        const result = response
        if (+result.code === 200) {
          if (type === '1') { // 新增(分为月工资和补发)
            const resultData = result.data.hrSalaryMonths || []

            console.log('获取员工资料后，查看路由参数')
            console.log(this.paramsData)

            // let list = JSON.parse( JSON.stringify(this.listData) );

            this.listData = resultData.map((item) => {
              item.baseSalary = item.salaryBase
              item.assessmentSalary = item.salaryAssessment
              item.postSalary = item.salaryPost
              item.allowanceSalary = item.salaryAllowance
              return item
            })

            // 如果是点击补发工资进来的，就去掉本页面所有的数据，放到选择员工中去
            if (this.paramsData.salaryType == 20) {
              	const list = JSON.parse(JSON.stringify(this.listData))
              	this.empchooseInfo.datalist = list
              	this.listData = []
            }

            // 新增的时候自动生产一个标题
            const year = this.paramsData.salaryDate.substring(0, 4)
            const month = this.paramsData.salaryDate.substring(5, 7)

            this.paramsData.title = `${year}年${month}月-${result.data.deptName}-`
	          if (this.paramsData.salaryType == 10) {
		    		this.paramsData.title += '月薪发放'
		    	} else if (this.paramsData.salaryType == 20) {
		    		this.paramsData.title += '工资补发'
		    	} else if (this.paramsData.salaryType == 11) {
		    		this.paramsData.title += '月薪发放'
		    	}
          } else { // 修改和查看
            this.listData = result.data.hrSalaryMonths || []
            this.searchKey.deptId = result.data.deptId
            this.searchKey.salaryDate = formatDate(result.data.salaryMonth, 'yyyy-MM-dd')

            // 重置一下这个页面的salaryType，就是返回数据的salaryType
            // console.log(111);
            // console.log( this.listData)
            if (this.listData[0]) {
              	// console.log('修改返回')
              	// console.log(this.listData[0])
              	this.paramsData.title = result.data.title
              	this.paramsData.salaryType = result.data.salaryType

              	this.paramsData.deptId = result.data.deptId
              	this.paramsData.salaryMonth = result.data.salaryMonth

              	console.log(this.paramsData)

              // 修改也要加载备选数据
              /* let list = [];
               let response = await getEmployeeListCreateAPI({
				              ...searchKey
				            })
               list = response.data.hrSalaryMonths

               this.empchooseInfo.datalist = list;*/
            }
          }
          this.totalCount = result.data.hrSalaryMonths.length
          this.deptName = result.data.deptName
        } else if (+result.code === 500) {
          this.$router.go(-1)
          this.$notify.error({
            title: '错误',
            message: result.msg || '获取列表失败！'
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: result.msg || '获取列表失败！'
          })
        }
      } catch (error) {
        // console.log(error)
        this.$notify.error({
          title: '错误',
          message: error.message || '获取列表失败!'
        })
      } finally {
        this.listLoading = false
      }
    },
    async initUpload() { // 初始化上传
      if (this.importInstance) this.importInstance.destroy()

      this.$nextTick(() => {
        // 导入初始化
        if (this.id || true) {
          this.initPlupload({
            container: 'import-box',
            selectFiles: 'upload-import',
            params: {
              submissionId: this.id
            }
          }).then((instance) => {
            this.importInstance = instance
            this.importInstance.init()
            this.importInstance.bind('handleAddFile', (up, result) => {
              up.splice(0, 1)

              this.$confirm('文档已经解析成功，是否确认导入数据?注意：导入后列表已有数据将被清空！！', '警告', {
		            confirmButtonText: '确定',
		            cancelButtonText: '取消',
		            type: 'warning'
		          }).then(async() => {
		           // 清空原有数据
	                this.listData = result.data || []
	                this.totalCount = result.data.length
		          }).catch(() => {})
            })
          }).catch((error) => {
            // this.$alert(error.msg, "错误'", { dangerouslyUseHTMLString: true });

            this.$notify.error({
              title: '错误',
              message: error.message,
              dangerouslyUseHTMLString: true
            })
          })
        }
      })
    },

    // 由别的页面跳转到月薪制作页面，参数的预处理  marked by yyf
    async initBeforeRoute(obj, to, from) { // 初始化页面
      const { id, type = '1', deptId, salaryDate, salaryType, title } = to.query
      obj.type = type
      obj.id = id
      obj.searchKey.deptId = deptId
      obj.searchKey.salaryDate = salaryDate
      obj.paramsData = to.query
      obj.paramsData.deptId = deptId
      obj.paramsData.salaryDate = salaryDate // 如果是修改的话，还得去修改查询那里去想办法
      // console.log(obj.paramsData);
      if (type === '1') { // 新增
        if (deptId && salaryDate) {
          obj.isShowSelectParams = false
          obj.getListData() // 新增的话，就默认加载需要的员工数据
        } else {
          obj.isShowSelectParams = true
        }
        obj.getDepartmentAllListData()
      } else { // 修改、查看
        if (id) {
          obj.isShowSelectParams = false
          obj.getListData()
          if (type === '2') { // 只有修改才有导入
            this.initUpload()
          }
        } else {
          this.$router.go(-1)
        }
      }
    },
    async initData() { // 初始化数据
      this.getListData()
      this.getDepartmentAllListData()
    }
  },
  beforeRouteEnter(to, from, next) {
    // console.log(to)
    // console.log(from)
    next(vm => {
      vm.initBeforeRoute(vm, to, from)
    })
  },
  beforeRouteUpdate(to, from, next) {
    // console.log(to)
    // console.log(from)
    this.initBeforeRoute(this, to, from)
    next()
  }
}
</script>

<style lang="scss" scoped>
</style>
